<?php
namespace tlan_turing\service;

use think\App;
use think\facade\Config;
use think\Request;
use think\response\{Json , Jsonp};
use think\facade\Db;
trait  JsonService
{

    protected Request $request;

    protected array $result = [
        'code'      =>  1,
        'message'   =>  '',
        'data'      =>  '',
    ];

    public function __construct( protected App $app)
    {
        $this->request = $this->app->request;
    }



    public function success(
        mixed $message = "SUCCESS",
        array | object $data = [],
        int $code   = 1,
        int $show   = 0,
    )
    {
        $this->result = [
            'code'  =>  $code,
            'show'  =>  $show,
        ];

        if(is_array($message) || is_object($message))
        {
            $data = $message;
            $this->result['message'] = 'SUCCESS';
        } else{
            $this->result['message'] = $message;
            $this->result['data']    = $data;
        }
        return $this->result($data);
    }

    public function fail(
        mixed $message = "ERROR",
        array | object $data = [],
        int $code       =   0,
        int $show       = 0,
    )
    {
        $this->result = [
            'code'  =>  $code ,
            'show'  =>  $show,
            'message'   =>  $message
        ];
        return $this->result($data);
    }



    protected function result(
        mixed $data
    )
    {


        if (is_object($data))
        {
            if ($data instanceof \think\db\Query )
            {
                $this->result['data'] = [
                    'lists'     =>  $data->select(),
                    'count'     =>  $data->count(),
                    'page'      =>  $this->request->get('page/d' , 1),
                    'page_size' =>  $this->request->get('page_size/d' , 15),
//                    'options'   =>  $data->getOptions(),
                ];

                if(env('APP_DEBUG') == true)
                    $this->result['sql']    = $data->fetchSql(true)->select();

            }

        }else if(is_array($data))
        {
            $this->result['data'] = $data;
        }
        return response(type: 'json')->data($this->result)->code(200);
    }

}